import React, { createContext, useState, useEffect, useContext } from 'react';

const AuthContext = createContext();

export function useAuth() {
    return useContext(AuthContext);
}

export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState(null);
    const [loading, setLoading] = useState(true);

    // Check if user is logged in from localStorage on initial load
    useEffect(() => {
        const user = localStorage.getItem('user');
        if (user) {
            setCurrentUser(JSON.parse(user));
        }
        setLoading(false);
    }, []);

    // Mock login function (in a real app, this would call an API)
    const login = async (email, password) => {
        // Simulate API call
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // This is just for demo purposes
                if (email === 'demo@example.com' && password === 'password') {
                    const user = {
                        id: '1',
                        name: 'Demo User',
                        email: 'demo@example.com',
                        avatar: 'https://i.pravatar.cc/150?img=1'
                    };

                    setCurrentUser(user);
                    localStorage.setItem('user', JSON.stringify(user));
                    resolve(user);
                } else {
                    reject(new Error('Invalid email or password'));
                }
            }, 1000);
        });
    };

    // Mock register function
    const register = async (name, email, password) => {
        // Simulate API call
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // This is just for demo purposes
                const user = {
                    id: '1',
                    name: name,
                    email: email,
                    avatar: 'https://i.pravatar.cc/150?img=1'
                };

                setCurrentUser(user);
                localStorage.setItem('user', JSON.stringify(user));
                resolve(user);
            }, 1000);
        });
    };

    // Logout function
    const logout = () => {
        setCurrentUser(null);
        localStorage.removeItem('user');
    };

    const value = {
        currentUser,
        login,
        register,
        logout,
        isAuthenticated: !!currentUser
    };

    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    );
} 